'''
#银行管理系统
class Card:  
    def __init__(self, card_number, pin, balance=0.0):  
        self.card_number = card_number  
        self.pin = pin  
        self.balance = balance  
  
    def deposit(self, amount):  
        if amount > 0:  
            self.balance += amount  
            print(f"Successfully deposited {amount}. New balance is {self.balance}.")  
        else:  
            print("Deposit amount must be positive.")  
  
    def withdraw(self, amount):  
        if 0 < amount <= self.balance:  
            self.balance -= amount  
            print(f"Successfully withdrew {amount}. New balance is {self.balance}.")  
        else:  
            print("Invalid amount or insufficient funds.")  
  
    def get_balance(self):  
        return self.balance  
  
    def transfer(self, other_card, amount):  
        if 0 < amount <= self.balance:  
            self.withdraw(amount)  
            other_card.deposit(amount)  
            print(f"Successfully transferred {amount} to card {other_card.card_number}.")  
        else:  
            print("Invalid amount or insufficient funds.")  
  
    def lock(self):  
        self.is_locked = True  
        print("Card locked.")  
  
    def unlock(self, pin):  
        if pin == self.pin:  
            self.is_locked = False  
            print("Card unlocked.")  
        else:  
            print("Invalid PIN.")  





class User:  
    def __init__(self, user_id, name, card=None):  
        self.user_id = user_id  
        self.name = name  
        self.card = card if card else Card(f"Card{user_id}", f"PIN{user_id}")  
  
    def get_card(self):  
        return self.card  







class ATM:  
    def __init__(self):  
        self.users = {}  
  
    def create_account(self, user_id, name):  
        if user_id not in self.users:  
            user = User(user_id, name)  
            self.users[user_id] = user  
            print(f"Account created for {name} with user ID {user_id}.")  
        else:  
            print("Account already exists.")  
  
    def query_balance(self, user_id):  
        user = self.users.get(user_id)  
        if user:  
            print(f"Balance for {user.name}: {user.get_card().get_balance()}")  
        else:  
            print("User not found.")  
  
    def deposit(self, user_id, amount):  
        user = self.users.get(user_id)  
        if user:  
            user.get_card().deposit(amount)  
        else:  
            print("User not found.")  
  
    def withdraw(self, user_id, amount):  
        user = self.users.get(user_id)  
        if user:  
            user.get_card().withdraw(amount)  
        else:  
            print("User not found.")  
  
    def transfer(self, from_user_id, to_user_id, amount):  
        from_user = self.users.get(from_user_id)  
        to_user = self.users.get(to_user_id)  
        if from_user and to_user:  
            from_user.get_card().transfer(to_user.get_card(), amount)  
        else:  
            print("One or both users not found.")  
  
    def lock_card(self, user_id):  
        user = self.users.get(user_id)  
        if user:  
            user.get_card().lock()  
        else:  
            print("User not found.")  
  
    def unlock_card(self, user_id, pin):  
        user = self.users.get(user_id)  
        if user:  
            user.get_card().unlock(pin)  
        else:  
            print("User not found.")  





class Admin:  
    def __init__(self, username, password):  
        self.username = username  
        self.password = password  
  
    def authenticate(self, entered_username, entered_password):  
        return self.username == entered_username and self.password == entered_password  






class HomePage:  
    def __init__(self, admin):  
        self.admin = admin  
        self.atm = ATM()  
  
    def display_welcome_screen(self):  
        print("Welcome to the Bank Management System!")  
  
    def display_menu(self):  
        print("\nATM Services Menu:")  
        print("1. Create Account")  
        print("2. Query Balance")  
        print("3. Deposit")  
        print("4. Withdraw")  
        print("5. Transfer")  
        print("6. Lock Card")  
        print("7. Unlock Card")  
        print("Q. Exit")  
  
    def run(self):  
        self.display_welcome_screen()  
        if self.admin.authenticate("admin", "admin_password"):  # Example credentials  
            print("Login successful!")  
            while True:  
                self.display_menu()  
                choice = input("Enter your choice: ").strip().upper()  
  
                if choice == '1':  
                    user_id = input("Enter user ID: ").strip()  
                    name = input("Enter user name: ").strip()  
                    self.atm.create_account(user_id, name)  
                elif choice == '2':  
                    user_id = input("Enter user ID: ").strip()  
                    self.atm.query_balance(user_id)  
                elif choice == '3':  
                    user_id = input("Enter user ID: ").strip()  
                    amount = float(input("Enter deposit amount: ").strip())  
                    self.atm.deposit(user_id, amount)  
                elif choice == '4':  
                    user_id = input("Enter user ID: ").strip()  
                    amount = float(input("Enter withdrawal amount: ").strip())  
                    self.atm.withdraw(user_id, amount)  
                elif choice == '5':  
                    from_user_id = input("Enter from user ID: ").strip()  
                    to_user_id = input("Enter to user ID: ").strip()  
                    amount = float(input("Enter transfer amount: ").strip())  
                    self.atm.transfer(from_user_id, to_user_id, amount)  
                elif choice == '6':  
                    user_id = input("Enter user ID: ").strip()  
                    self.atm.lock_card(user_id)  
                elif choice == '7':  
                    user_id = input("Enter user ID: ").strip()  
                    pin = input("Enter PIN to unlock: ").strip()  
                    self.atm.unlock_card(user_id, pin)  
                elif choice == 'Q':  
                    print("Exiting the system. Goodbye!")  
                    break  
                else:  
                    print("Invalid choice. Please try again.")  
        else:  
            print("Invalid credentials. Access denied.")  
  
# Example usage  
admin = Admin("admin", "admin_password")  
home_page = HomePage(admin)  
home_page.run()


'''










'''




#井字棋 
import random
import tkinter as tk
from tkinter import messagebox


def draw_grid(canvas):
    # 画外边框线
    canvas.create_line(2, 2, 300, 2, width=2)  # 上
    canvas.create_line(2, 2, 2, 300, width=2)  # 左
    canvas.create_line(2, 300, 300, 300, width=2)  # 下
    canvas.create_line(300, 2, 300, 300, width=2)  # 右
    # 画横线
    canvas.create_line(100, 0, 100, 300)
    canvas.create_line(200, 0, 200, 300)
    # 画竖线
    canvas.create_line(0, 100, 300, 100)
    canvas.create_line(0, 200, 300, 200)

    num = 1
    for i in range(3):
        for j in range(3):
            y = i * 100 + 50
            x = j * 100 + 50
            canvas.create_text(x, y, text=str(num), font=("Arial", 24))

            num += 1


def on_click():
    global board
    global step
    position = e1.get()

    if position.isdigit() and 1 <= int(position) <= 9:
        number = int(position)
        index = number - 1
        if board[index] == ' ':
            board[index] = 'x'
            x = ((int(position) - 1) % 3) * 100 + 50
            y = ((int(position) - 1) // 3) * 100 + 50
            canvas.create_line(x - 20, y - 20, x + 20, y + 20, fill='black', width=2)
            canvas.create_line(x + 20, y - 20, x - 20, y + 20, fill='black', width=2)
            step += 1
            iswins()
            if not gameover:
                ai_move()
        else:
            messagebox.showerror("错误", "该位置已经落子，请选择其他位置")



    

def ai_move():
    global board, foot
    index = random.randint(0, 8)

    while board[index] != ' ':
        index = random.randint(0, 8)

    x = ((index) % 3) * 100 + 50
    y = ((index) // 3) * 100 + 50

    canvas.create_oval(x - 20, y - 20, x + 20, y + 20, fill='red')
    board[index] = 'AI'
    foot += 1
    iswins()


def problem():
    try:
        input_value = int(e1.get())
        if input_value < 1 or input_value > 9:
            messagebox.showerror("错误", "请输入1到9之间的数字")
        else:
            print("输入正确")
    except ValueError:
        messagebox.showerror("错误", "请输入一个有效的数字")

    on_click()


def iswins():
    global gameover,step
    wins = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
    for w in wins:
        if (board[w[0]]!=" " and board[w[0]]==board[w[1]]==board[w[2]]):
            gameover = True
            messagebox.showinfo(title="shuchu",message="赢家是"+board[w[0]])
            return
    if step>5:
        gameover = True
        messagebox.showinfo(title="shuchu",message="都没有赢了")
    return

def again():
    global board, step, gameover
    board = [' '] * 9
    step = 0
    gameover = False
    canvas.delete('all')
    draw_grid(canvas)



def main():
    root = tk.Tk()
    root.title("九宫格")
    root.geometry("500x600")

    lb1 = tk.Label(root, text='请要输入落子的位置(1~9):')
    lb1.place(x=150, y=350)
    global e1
    e1 = tk.Entry(root, bd=5, width=20)
    e1.place(x=150, y=380)
    button1 = tk.Button(root, text="按下落子", width=10, height=2, fg='black', command=problem)
    button1.place(x=180, y=420)
    button2 = tk.Button(root, text="重新开始", width=10, height=2, fg='black', command=again)
    button2.place(x=180, y=480)

    global canvas
    canvas = tk.Canvas(root, width=350, height=350,)
    canvas.pack()

    draw_grid(canvas)

    root.mainloop()


if __name__ == "__main__":
    board = [' '] * 9
    gameover = False
    step = 0

    foot =0
    main()

'''










import random  
  
class Board:  
    def __init__(self):  
        self.board = [[' ' for _ in range(3)] for _ in range(3)]  
  
    def show_board(self):  
        print("  0 1 2")  
        for i, row in enumerate(self.board):  
            print(f"{i} {' '.join(row)}")  
  
    def get_position_name(self, row, col):  
        return f"{row}{col}"  
  
    def is_position_valid(self, row, col):  
        return 0 <= row < 3 and 0 <= col < 3 and self.board[row][col] == ' '  
  
    def place_marker(self, row, col, marker):  
        self.board[row][col] = marker  
  
    def check_win(self, marker):  
        # Check rows  
        for row in self.board:  
            if all(cell == marker for cell in row):  
                return True  
        # Check columns  
        for col in range(3):  
            if all(self.board[row][col] == marker for row in range(3)):  
                return True  
        # Check diagonals  
        if all(self.board[i][i] == marker for i in range(3)):  
            return True  
        if all(self.board[i][2-i] == marker for i in range(3)):  
            return True  
        return False  
  
    def is_draw(self):  
        return all(cell != ' ' for row in self.board for cell in row)  
  
        
    def get_empty_positions(self):  
        return [(i, j) for i in range(3) for j in range(3) if self.board[i][j] == ' ']  
  
  


class Player:  
    def __init__(self, name, marker):  
        self.name = name  
        self.marker = marker  
        self.score = 0  
  
    def place_marker(self, board, row, col):  
        board.place_marker(row, col, self.marker)  
  
  




class AIPlayer(Player):  

    def place_marker(self, board, human_marker):  
        empty_positions = board.get_empty_positions()  
          
        # Check for winning move  
        for pos in empty_positions:  
            row, col = pos  
            board.place_marker(row, col, self.marker)  
            if board.check_win(self.marker):  
                return pos  
            board.place_marker(row, col, ' ')  
          
        # Block losing move  
        for pos in empty_positions:  
            row, col = pos  
            board.place_marker(row, col, human_marker)  
            if board.check_win(human_marker):  
                board.place_marker(row, col, ' ')  
                board.place_marker(row, col, self.marker)  
                return pos  
            board.place_marker(row, col, ' ')  
          
        # Evaluate positions based on strategy  
        center_position = (1, 1)  
        corner_positions = [(0, 0), (0, 2), (2, 0), (2, 2)]  
        edge_positions = [(0, 1), (1, 0), (1, 2), (2, 1)]  
          
        if center_position in empty_positions:  
            return center_position  
        elif any(pos in empty_positions for pos in corner_positions):  
            return random.choice([pos for pos in corner_positions if pos in empty_positions])  
        elif any(pos in empty_positions for pos in edge_positions):  
            return random.choice([pos for pos in edge_positions if pos in empty_positions])  
  
  



class Game:  
    def __init__(self):  
        self.board = Board()  
        self.human_player = Player("Human", 'O')  
        self.ai_player = AIPlayer("AI", 'X')  
        self.human_score = 0  
        self.ai_score = 0  
  
    def start_game(self):  
        while True:  
            self.board.show_board()  
            current_player = self.human_player if self.board.get_empty_positions() else None  
              
            if current_player == self.human_player:  
                row = int(input("Enter row (0, 1, 2): "))  
                col = int(input("Enter col (0, 1, 2): "))  
                  
                while not self.board.is_position_valid(row, col):  
                    print("Invalid position. Try again.")  
                    row = int(input("Enter row (0, 1, 2): "))  
                    col = int(input("Enter col (0, 1, 2): "))  
                  
                self.human_player.place_marker(self.board, row, col)  
                  
                if self.board.check_win(self.human_player.marker):  
                    print(f"{self.human_player.name} wins!")  
                    self.human_score += 1  
                    break  
                elif self.board.is_draw():  
                    print("该位置已经被占领!")  
                    break  
                else:  
                    current_player = self.ai_player  
              
            if current_player == self.ai_player:  
                pos = self.ai_player.place_marker(self.board, self.human_player.marker)  
                row, col = pos  
                print(f"{self.ai_player.name} places marker at {self.board.get_position_name(row, col)}")  
                  
                if self.board.check_win(self.ai_player.marker):  
                    print(f"{self.ai_player.name} wins!")  
                    self.ai_score += 1  
                    break  
                elif self.board.is_draw():  
                    print("It's a draw!")  
                    break  
  
            self.board.show_board()  
  
        print(f"Final Score: Human - {self.human_score}, AI - {self.ai_score}")  
  
  


  
if __name__ == "__main__":  
    game = Game()  
    game.start_game()







